package org.mspring.mlog.service.impl;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;

import org.apache.commons.io.FilenameUtils;
import org.mspring.mlog.service.StorageService;
import org.mspring.mlog.service.exception.StorageException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 
 * @author Gao Youbo
 * @since 2013年11月23日
 */
@Service
public class PhotoUploadServiceImpl extends AbstractPhotoUploadService {
    @Autowired
    private StorageService storageService;

    @Override
    public String uploadPhoto(BufferedImage image, String filename) throws IOException, StorageException {
        // TODO Auto-generated method stub
        String formatName = FilenameUtils.getExtension(filename);

        try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            ImageIO.write(image, formatName, bos);
            byte[] bytearray = bos.toByteArray();
            try (InputStream inputStream = new ByteArrayInputStream(bytearray)) {
                return storageService.put(filename, inputStream);
            }
        }
    }
}
